package com.pangus.ims.mes.service;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aspose.slides.p2cbca448.ifd;
import com.pangus.common.dto.JqGridRequest;
import com.pangus.common.dto.JqGridResponse;
import com.pangus.common.excel.callback.ExcelCallbackService;
import com.pangus.common.sys.service.DataRolePointService;
import com.pangus.common.sys.utils.CommonUtils;
import com.pangus.common.sys.utils.ParamUtils;
import com.pangus.common.sys.utils.PartnerCodeHolder;
import com.pangus.common.sys.utils.SqlQueryUtils;
import com.pangus.fa.service.BaseService;
import com.pangus.ims.file.FileUtils;
import com.pangus.ims.mes.dto.domain.MesProdExchConfigDto;
import com.pangus.ims.mes.form.MesProdExchConfigForm;

@Service
public class MesMoExchConfigService extends BaseService<MesProdExchConfigDto> implements ExcelCallbackService<MesProdExchConfigForm>{

	@Autowired
	private SqlQueryUtils sqlQueryUtils;
	@Autowired
    private DataRolePointService dataRolePointService;
	
	@Override
	public JqGridResponse<MesProdExchConfigForm> query(JqGridRequest<MesProdExchConfigForm> request,
			ParamUtils paramUtils) {
		String partnerCode = PartnerCodeHolder.getPartnerCode();
		String pointData = dataRolePointService.getSql(paramUtils.getUserCode(), "MesProdExchConfig.Query");
		String sql = getQuerySql();
		sql += " where  m.mo_id is not null ";
		sql = CommonUtils.addCondition(sql, "m.", pointData, partnerCode,paramUtils);
		return sqlQueryUtils.queryByCondition(request, sql, MesProdExchConfigForm.class);
	}
	
	/**
	 * 根据产品编码查询图片路径
	 * @author ruiming2
	 */
	public List<String> getProdImages(String prodCode, HttpServletRequest request) {
		//获取http、ip、端口号、项目名
		String protocol = request.getScheme();
		String serverIp = request.getServerName();
		int serverPort = request.getServerPort();
		String worString = request.getContextPath();//"/ims-mes/"
		String urlPrefix = protocol + "://" + serverIp + ":" + serverPort + worString + '/';
		//获取绝对路径
		String prodPath = FileUtils.getSavePath("/fileUpload/logo/mtrl/" + prodCode, request);
		//构建文件夹路径
		File folder = new File(prodPath);
		//获取该文件夹下的所有内容(上传已经过滤掉不是图片文件的数据了)
		List<String> imagePaths = new ArrayList<>();
		//检查是否存在并且是一个目录
		if (folder.exists() && folder.isDirectory()) {
			//获取该路径下的所有子目录和文件
			File[] files = folder.listFiles((dir, name) -> isImageFile(new File(dir, name)));
			if (files != null) {
				//增强 for
				for (File file : files) {
					String filePath = file.getAbsolutePath();
					String safeFilePath = filePath.substring(filePath.indexOf("fileUpload")).replace(File.separator,"/");;
					String newFilePath = urlPrefix + safeFilePath;
					imagePaths.add(newFilePath);
				}
			}
		}
		return imagePaths;
	}
	
	/**
	 * 判断文件数据是否是图片类型
	 * @author ruiming2
	 */
	private boolean isImageFile(File file) {
		try {
			//获取文件的 MIME 类型
			String mimeType = Files.probeContentType(file.toPath());
			//判断 MIME 类型是否为图像类型
			return mimeType != null && mimeType.startsWith("image/");
		} catch (Exception e) {
			// 如果无法获取 MIME 类型，则判断不是图像文件
			return false;
		}
	}

	/**
	*查询本表sql
	*根据orgid是否关联组织表
	*/
	public String getQuerySql() {
		String sql = "SELECT "+
				" bp.PHASE_CODE,tp.tp_name,tp.tp_id,tp.tp_code,bmo.erp_mo, "+
				" m.prog_path, "+
				" m.chip_check, "+
				" bp.PHASE_NAME , "+
				" b.MTRL_CODE prod_code, "+
				" b.MTRL_DESC prod_DESC, "+
				" b.MTRL_NAME prod_name, "+
				" m.mes_prod_exch_config_id, "+
				" m.org_id, "+
				" m.prod_id, "+
				" m.mo_id, "+
				" m.prod_type_id, "+
				" m.prod_machine_id, "+
				" m.phase_id, "+
				" m.prod_id_ext, "+
				" m.prod_source_sn, "+
				" m.prod_sn_rule, "+
				" m.prod_pack_num, "+
				" m.prod_case_num, "+
				" m.age_time, "+
				" m.weight_mnuit, "+
				" m.weight_min, "+
				" m.weight_max, "+
				" m.plan_data, "+
				" m.mes_prod_plan_hd_id, "+
				" m.remark, "+
				" u.user_name as created_by, "+
				" m.created_date, "+
				" u2.user_name as updated_by, "+
				" m.updated_date, "+
				" m.mes_prod_exch_config_ex1, "+
				" m.mes_prod_exch_config_ex2, "+
				" m.mes_prod_exch_config_ex3, "+
				" m.mes_prod_exch_config_ex4, "+
				" m.mes_prod_exch_config_ex5, "+
				" m.mes_prod_exch_config_ex6, "+
				" m.mes_prod_exch_config_ex7, "+
				" m.mes_prod_exch_config_ex8, "+
				" m.mes_prod_exch_config_ex9 , "+
				" m.SOP_PATH1,m.SOP_RESULT_TYPE1,m.SOP_RESULT1,m.SOP_TIME1,m.IS_OLD_ADAPT_IPC, " +
				" c.message_key org_name,bmo.mo_code, "+
				" mpec.prod_machine_name,mpec.prod_machine_code,bmt.mtype_code prod_type_code, "+
				" m.cust_id,cust.CUST_CODE " +
				" FROM "+
				"	mes_prod_exch_config m "+
				" LEFT JOIN ims_company c ON "+
				"	c.company_code = m.org_id "+
				"	AND c.partner_code = {partnerCode} "+
				" LEFT JOIN bs_mtrl b ON "+
				"	b.mtrl_id = m.PROD_ID "+
				" LEFT JOIN BS_PHASE bp ON "+
				"	bp.phase_id = m.PHASE_ID "+
				" LEFT JOIN bs_prod_machine_type mpec ON m.prod_machine_id = mpec.bs_prod_machine_type_id  "+
				" LEFT JOIN BS_MTRL_TYPE bmt on bmt.mtype_id = m.prod_type_id "+
				" LEFT JOIN BS_TP tp on tp.tp_id = m.tp_id "+
				" left join bs_mo bmo on bmo.mo_id=m.mo_id "+
				" LEFT JOIN IMS_USER u on u.user_id = m.created_by "+
				" LEFT JOIN IMS_USER u2 on u2.user_id = m.updated_by "+
				" LEFT JOIN BS_CUST cust ON cust.CUST_ID = m.CUST_ID ";
		return sql;
	}
	@Override
	public void importConvert(int i, List<MesProdExchConfigForm> list, ParamUtils paramUtils) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void exportConvert(int j, List<MesProdExchConfigForm> list, ParamUtils paramUtils) {
		// TODO Auto-generated method stub
		
	}
	
	public MesProdExchConfigForm queryByMoId(String moId,ParamUtils paramUtils){
		String sql = getQuerySql();
		sql += " where  m.mo_id = ? ";
		String partnerCode = PartnerCodeHolder.getPartnerCode();
		String pointData = dataRolePointService.getSql(paramUtils.getUserCode(), "MesProdExchConfig.Query");
		sql = CommonUtils.addCondition(sql, "m.", pointData, partnerCode, paramUtils);
		return sqlQueryUtils.get(sql, new Object[] { moId},MesProdExchConfigForm.class);
	}

}
